<?php
namespace App\Controllers\Sys;

use App\Controllers\BaseController;
use App\Models\SysRole;
use App\Models\SysMenu;

class RoleController extends BaseController {

    public function initialize() {
        parent::initialize();
    }

    //----------------------------------------------------------------
    // 角色信息列表
    //----------------------------------------------------------------
    public function indexAction() {
        $this->display('sys/role/index');
    }

    //----------------------------------------------------------------
    // 获取角色信息
    //----------------------------------------------------------------
    public function getsAction() {
        $role  = new SysRole();
        $roles = $role->gets();
        if($roles !== false) {
            foreach($roles as $k => $v) {
                $purview = json_decode($v['purview'], true);
                $html    = '';
                foreach($purview as $_v) {
                    $html .= '<i class="' . $_v['icon'] . '"></i><span title="' . $_v['url'] . '">' . $_v['title'] . '</span>';
                    $addLow = false;
                    foreach($_v['submenus'] as $__v) {
                        if(!$addLow) {
                            $html .= '<br/>　└';
                            $addLow = true;
                        }
                        $html .= '&nbsp;&nbsp;<i class="' . $__v['icon'] . '"></i><span title="' . $__v['url'] . '">' . $__v['title'] . '</span>';
                    }
                    $html .= '<br/>';
                }
                $roles[$k]['purview'] = $html;
            }
        }
        if($roles) {
            return $this->sendAjax(true, $roles);
        } else {
            return $this->sendAjax(false, "获取数据失败，系统错误！");
        }
    }

    public function getAction() {
        $id = $this->request->getPost('id') != '' ? $this->request->getPost('id') : $this->request->getQuery('id');
        if($id == '' || !is_numeric($id)) {
            return $this->sendAjax(false, '编辑失败，获取角色的Id失败！');
        }
        $role   = new SysRole();
        $id     = intval($id);
        $entity = $role->get($id);
        if($entity === false || !is_array($entity)) {
            return $this->sendAjax(false, '编辑失败，获取角色信息失败！');
        }
        $menu     = new SysMenu();
        $retMenus = $menu->getRoleMenus();
        if($retMenus === false || !is_array($retMenus)) {
            return $this->sendAjax(false, '编辑失败，获取菜单失败！');
        }
        $purview = json_decode($entity['purview'], true);
        if($purview === false || !is_array($purview)) {
            return $this->sendAjax(false, '编辑失败，获取角色的权限失败！');
        }

        $menus = [];
        foreach($retMenus as $k => $v) {
            $checked = 'n';
            if($v['up_id'] == 0) {
                if(isset($purview[$v['id']])) {
                    $checked = 'y';
                }
                $menus[$v['id']] = [
                    'id'       => $v['id'],
                    'name'     => $v['name'],
                    'url'      => $v['url'],
                    'icon'     => $v['icon'],
                    'checked'  => $checked,
                    'submenus' => []
                ];
            } else {
                if(isset($purview[$v['up_id']]) && isset($purview[$v['up_id']]['submenus'][$v['id']])) {
                    $checked = 'y';
                }
                $menus[$v['up_id']]['submenus'][$v['id']] = [
                    'id'      => $v['id'],
                    'name'    => $v['name'],
                    'url'     => $v['url'],
                    'icon'    => $v['icon'],
                    'checked' => $checked
                ];
            }
        }
        unset($entity['purview']);
        $k = 0;
        foreach($menus as $v) {
            $outMenus[$k] = $v;
            if(is_array($v['submenus']) && count($v['submenus']) > 0) {
                unset($outMenus[$k]['submenus']);
                foreach($v['submenus'] as $_v) {
                    $outMenus[$k]['submenus'][] = $_v;
                }
            }
            $k++;
        }
        return $this->sendAjax(true, [
            'role'  => $entity,
            'menus' => $outMenus
        ]);
    }

    //----------------------------------------------------------------
    // 添加角色的权限信息
    //----------------------------------------------------------------
    public function addAction() {
        if($this->request->isGet()) {
            $this->display('sys/role/add');
        } else {
            $data = [
                'name'    => $this->request->getPost('name'),
                'status'  => $this->request->getPost('status'),
                'purview' => str_replace('m-k', '', $this->request->getPost('menu'))
            ];
            if($data['name'] == '') {
                return $this->sendAjax(false, '添加角色权限信息失败，用户名不能为空！');
            }
            if($data['status'] == '' || !is_numeric($data['status']) || !in_array($data['status'], ['0', '1'])) {
                return $this->sendAjax(false, '添加角色权限信息失败，请选择角色状态！');
            }
            if($data['purview'] == '') {
                return $this->sendAjax(false, '添加角色权限信息失败，权限序列化列表不能为空！');
            }

            $role = new SysRole();

            $retCheck = $role->isExists($data['name']);
            if($retCheck === -500) {
                return $this->sendAjax(false, '添加角色权限信息失败，系统错误！');
            }
            if($retCheck) {
                return $this->sendAjax(false, '添加角色权限信息失败，已经存在相同的角色名称！');
            }
            $ret = $role->add($data);
            if($ret !== false) {
                return $this->sendAjax(true, '添加角色权限信息成功！');
            } else {
                return $this->sendAjax(false, '添加角色权限信息失败，系统错误！');
            }
        }
    }

    //----------------------------------------------------------------
    // 编辑角色的权限信息
    //----------------------------------------------------------------
    public function editAction() {
        if($this->request->isGet()) {
            $this->display('sys/role/edit');
        } else {
            $data = [
                'id'      => $this->request->getPost('id'),
                'name'    => $this->request->getPost('name'),
                'status'  => $this->request->getPost('status'),
                'purview' => str_replace('m-k', '', $this->request->getPost('menu'))
            ];
            if($data['id'] == '' || !is_numeric($data['id'])) {
                return $this->sendAjax(false, '编辑角色权限信息失败，角色Id丢失！');
            }
            if($data['name'] == '') {
                return $this->sendAjax(false, '编辑角色权限信息失败，用户名不能为空！');
            }
            if($data['status'] == '' || !is_numeric($data['status']) || !in_array($data['status'], ['0', '1'])) {
                return $this->sendAjax(false, '添加角色权限信息失败，请选择角色状态！');
            }
            if($data['purview'] == '') {
                return $this->sendAjax(false, '添加角色权限信息失败，权限序列化列表不能为空！');
            }

            $role = new SysRole();

            $retCheck = $role->isExists($data['name'], $data['id']);
            if($retCheck === -500) {
                return $this->sendAjax(false, '添加角色权限信息失败，系统错误！');
            }
            if($retCheck) {
                return $this->sendAjax(false, '添加角色权限信息失败，已经存在相同的角色名称！');
            }
            $ret = $role->edit($data);
            if($ret !== false) {
                return $this->sendAjax(true, '编辑角色权限成功!');
            } else {
                return $this->sendAjax(false, '编辑角色权限失败，系统错误！');
            }
        }
    }

    //----------------------------------------------------------------
    // 获取所有的菜单并整合
    //----------------------------------------------------------------
    public function getMenusAction() {
        $menu     = new SysMenu();
        $retMenus = $menu->getRoleMenus();
        if($retMenus === false || !is_array($retMenus) || count($retMenus) == 0) {
            return $this->sendAjax(false, '编辑失败，获取菜单失败！');
        }
        $menus = [];
        foreach($retMenus as $k => $v) {
            if($v['up_id'] == '0') {
                $menus[$v['id']] = [
                    'id'       => $v['id'],
                    'name'     => $v['name'],
                    'url'      => $v['url'],
                    'icon'     => $v['icon'],
                    'submenus' => []
                ];
            } else {
                $menus[$v['up_id']]['submenus'][$v['id']] = [
                    'id'   => $v['id'],
                    'name' => $v['name'],
                    'url'  => $v['url'],
                    'icon' => $v['icon'],
                ];
            }
        }
        $k = 0;
        foreach($menus as $v) {
            $outMenus[$k] = $v;
            if(is_array($v['submenus']) && count($v['submenus']) > 0) {
                unset($outMenus[$k]['submenus']);
                foreach($v['submenus'] as $_v) {
                    $outMenus[$k]['submenus'][] = $_v;
                }
            }
            $k++;
        }
        return $this->sendAjax(true, [
            'role'  => '',
            'menus' => $outMenus
        ]);
    }
}

